#include "instancetcpserproc.h"
#include "ctaskproc.h"
#include "custombox.h"
#include "funcmgr.h"

InstanceTcpSerProc::InstanceTcpSerProc()
{
    InstanceTcpServer = new QTcpServer();

    ForwardIp = QSNULL;
    ForwardPort = 0;
    IsSerStart = false;
}

InstanceTcpSerProc::~InstanceTcpSerProc()
{
    delete InstanceTcpServer;
}

//启动转发监听服务
bool InstanceTcpSerProc::DoStart(QString ChoiceIp, quint16 LocalPort)
{
    if (IsSerStart)
        return true;

    //监听本地端口 等待连接
    if (!InstanceTcpServer->listen(QHostAddress::AnyIPv4, LocalPort))
    {
        IsSerStart = false;
        InstanceTcpServer->close();
        return false;
    }

    ForwardIp = ChoiceIp;
    ForwardPort = LocalPort;

    QObject::connect(InstanceTcpServer, SIGNAL(newConnection()), this, SLOT(AcceptConnect()));
    IsSerStart = true;
    return true;
}

void InstanceTcpSerProc::DoStop()
{
    if (IsSerStart)
    {
        IsSerStart = false;
        InstanceTcpServer->close();
    }
}

void InstanceTcpSerProc::AcceptConnect()
{
    if (!InstanceTcpServer)
        return;

    //从监听端口得到Socket
    QTcpSocket*  TcpSocket = InstanceTcpServer->nextPendingConnection();

    //初始化执行转发过程
    CtaskProc* TaskProc = new CtaskProc(TcpSocket, ForwardIp, ForwardPort);
    TaskProc->StartForwardProc();
}
